package com.fly.core.base.future;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.time.StopWatch;
import org.junit.jupiter.api.Test;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BasicFuture
{
    private static Random rand = new Random();
    
    static int getMoreData()
    {
        StopWatch clock = new StopWatch();
        clock.start();
        log.info("begin to start compute");
        try
        {
            TimeUnit.SECONDS.sleep(3);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        clock.stop();
        log.info("end to compute,passed {}ms", clock.getTime());
        return rand.nextInt(1000);
    }
    
    @Test
    public void test()
        throws ExecutionException, InterruptedException
    {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(BasicFuture::getMoreData);
        Future<Integer> f = future.whenComplete((v, e) -> {
            log.info("v:{}, e:{}", v, e);
        });
        log.info("{}", f.get());
    }
}